package com.netrust.quarz.hw;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.netrust.quarz.hw.http.RequestType;
import com.netrust.quarz.hw.token.OcUtils;
import com.netrust.quarz.utils.ProdUtils;
import com.netrust.quarz.utils.db.DbHelper;

/**
* @title 
* @description
* @author   lazite
* @version  v_1.0.0
* @date   2017年10月16日 下午3:23:40
*/
public class CommonHttp {
	
	private static final Logger log = LoggerFactory.getLogger(CommonHttp.class);

	
	/**
	 * 发送请求获取的原始字符串
	 * 
	 * @return
	 */
	public List<String> getServer(OcUtils oc) throws Exception{
		
		String token = oc.token();
		if(StringUtils.isBlank(token)){
			return null;
		}
		
		JSONObject json = JSONObject.parseObject(token);
        String tokenId = json.getString("data");
        
        List<String> list=Lists.newArrayList();
		try {
			HttpsClientUtil httpsClientUtil=new HttpsClientUtil();
	        Object objs = httpsClientUtil.sendRequest("/oc/v2.3/mo/server?limit=100&start=0", RequestType.GET, null, tokenId,oc.nodeConfig());
	        String values=String.valueOf(objs);	      	
        	CommonHttp.saveOrginal("server||"+oc.getMo().getOcIp(), values, new Date());
        	
        	list.add(values);
	        
        	if (StringUtils.isNoneBlank(values)&&JSON.parseObject(values).get("total")!=null) {
    			int total=JSON.parseObject(values).getIntValue("total");
				int start = 1;
				if (total>100) {
					int pageSize=(total/100)+1;
					for (int j = 1; j < pageSize; j++) {
						start=100*j;
						objs =httpsClientUtil.sendRequest("/oc/v2.3/mo/server?limit=100&start="+start, RequestType.GET, null, tokenId,oc.nodeConfig());												
						
						CommonHttp.saveOrginal("server||"+oc.getMo().getOcIp(), String.valueOf(objs), new Date());
						
						list.add(String.valueOf(objs));
					}
				}
				httpsClientUtil.sendRequest("/oc/v2.3/tokens",RequestType.DELETE,null,tokenId,oc.nodeConfig());
        	}
				
		} catch (Exception e) {
			CommonHttp.saveOrginal("exception||server||"+oc.getMo().getOcIp(), ProdUtils.exception(e), new Date());
        	throw e;
		}

		return list;
	}
	
	
	/**
	 * 获取指定服务器的运行状态及利用率
	 * @param oc
	 * @param objIds
	 * @return
	 */
	public String getServerRealTime(OcUtils oc, String objIds)throws Exception{
		String originalJson = null;
		
		String token = oc.token();
		if(StringUtils.isBlank(token)){
			return null;
		}
		
		JSONObject json = JSONObject.parseObject(token);
        String tokenId = json.getString("data");
        
        String kpi = "{\"virtrualkpi\":[\"cpuusage\",\"memusage\"]," + "\"diskstate\":[\"diskusage\"],"
				+ "\"commonstatus\":[\"status\"]}";
        
        String urlEncodeObjIds="";
        String urlEncodekpi="";
		try {
			urlEncodeObjIds = URLEncoder.encode(objIds,"utf-8");
			urlEncodekpi = URLEncoder.encode(kpi,"utf-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		
		try {
			Object serverList = new HttpsClientUtil().sendRequest("/oc/v2.3/monitors/server/realtime?&object_ids="+urlEncodeObjIds+ "&kpi_groups="+ urlEncodekpi, 
					RequestType.GET, null, tokenId,oc.nodeConfig());
			originalJson=String.valueOf(serverList);
			
			CommonHttp.saveOrginal("state||"+oc.getMo().getOcIp(), originalJson, new Date());
			
			new HttpsClientUtil().sendRequest("/oc/v2.3/tokens",RequestType.DELETE, null, tokenId,oc.nodeConfig());			
		} catch (Exception e) {
			CommonHttp.saveOrginal("exception||state||"+oc.getMo().getOcIp(),ProdUtils.exception(e), new Date());
			throw e;
		}
		return originalJson;
	}
	
	/**
	 * 获取历史告警
	 * @param token
	 * @param recordLineName
	 * @param nodeConf
	 * @return
	 */
	public List<String> getAlarmHistory(OcUtils oc,int start) throws Exception{
		int stateStart=start;
		String token = oc.token();
		if(StringUtils.isBlank(token)){
			return null;
		}
        JSONObject json = JSONObject.parseObject(token);
        String tokenId = json.getString("data");
        
        try {
        	HttpsClientUtil httpsClientUtil=new HttpsClientUtil();
        	
        	Object objs = httpsClientUtil.sendRequest("/oc/v2.3/alarms/history?limit=100&start="+start, RequestType.GET, null, tokenId,oc.nodeConfig());
        	String values=String.valueOf(objs);	    

        	CommonHttp.saveOrginal("alarm_history||"+oc.getMo().getOcIp(),values, new Date());
        	
        	List<String> list=Lists.newArrayList();
        	
        	list.add(values);
        	
        	if (StringUtils.isNotBlank(values)&&JSON.parseObject(values).get("total")!=null) {
    			int total=(int) JSON.parseObject(values).get("total");
				if (total>100) {
					int pageSize=((total-stateStart)/100)+1;
					for (int j = 1; j < pageSize; j++) {
						start+=100;
						objs = httpsClientUtil.sendRequest("/oc/v2.3/alarms/history?&limit=100&start="+start, RequestType.GET, null, tokenId,oc.nodeConfig());												
						
						CommonHttp.saveOrginal("alarm_history||"+oc.getMo().getOcIp(), String.valueOf(objs), new Date());
						
						list.add(String.valueOf(objs));
					}
				}
				httpsClientUtil.sendRequest("/oc/v2.3/tokens",RequestType.DELETE,null,tokenId,oc.nodeConfig());
        	}
        	        	
        	return list;
		} catch (Exception e) {
			CommonHttp.saveOrginal("exception||alarm_history||"+oc.getMo().getOcIp(),ProdUtils.exception(e), new Date());
			throw e;
		}
	}
	
	
	/**
	 * 获取待处理告警
	 * @param oc
	 * @return
	 */
	public  List<String> getAlarmRealTime(OcUtils oc)  throws Exception{
		String token = oc.token();
		if(StringUtils.isBlank(token)){
			return null;
		}
		
		JSONObject json = JSON.parseObject(token);
        String tokenId = json.getString("data");
        
        String filter="{\"and\":[{\"and\":[{\"=\":{\"mo_type\": \"CLOUD_VM\"}}]}]}";
        
        List<String> list=Lists.newArrayList();
        try {
        	HttpsClientUtil httpsClientUtil=new HttpsClientUtil();
        	
        	Object objs = httpsClientUtil.sendRequest("/oc/v2.3/alarms/current?&limit=100&start=0&filter="+URLEncoder.encode(filter,"utf-8"), RequestType.GET, null, tokenId,oc.nodeConfig());        	
        	String values=String.valueOf(objs);	      	
        	CommonHttp.saveOrginal("alarm_real||"+oc.getMo().getOcIp(), String.valueOf(values), new Date());
        	
        	list.add(values);
        	
        	if (StringUtils.isNotBlank(values)&&JSON.parseObject(values).get("total")!=null) {
        			int total=(int) JSON.parseObject(values).get("total");
    				int start = 1;
    				if (total>100) {
    					int pageSize=(total/100)+1;
    					for (int j = 1; j < pageSize; j++) {
    						start=100*j;
    						objs = httpsClientUtil.sendRequest("/oc/v2.3/alarms/current?&limit=100&start="+start+"&filter="+URLEncoder.encode(filter,"utf-8"), RequestType.GET, null, tokenId,oc.nodeConfig());												
    						
    						CommonHttp.saveOrginal("alarm_real||"+oc.getMo().getOcIp(), String.valueOf(objs), new Date());
    						
    						list.add(String.valueOf(objs));
    					}
    				}
    				httpsClientUtil.sendRequest("/oc/v2.3/tokens",RequestType.DELETE,null,tokenId,oc.nodeConfig());
			}
        
        } catch (Exception e) {
        	CommonHttp.saveOrginal("exception||alarm_real||"+oc.getMo().getOcIp(), ProdUtils.exception(e), new Date());
        	throw e;
		}
        
		return list;
	}
	
	

	
	
	private static void saveOrginal(String name,String txt,Date time) {
		//此处需要修改按照项目状况修改参数
		Connection conn = new DbHelper().getConnection();
		
		if(conn==null){					
			return;
		}
		
		QueryRunner qr = new QueryRunner();
		
		String sql = "insert into t_state_original_data(name,original_json,time) values (?,?,?)";
		
		try {
		    qr.update(conn,sql,name,txt,time);
		} catch (SQLException e) {
			log.error("数据库链接故障>>>>>",e);
		}finally {
			try {
				if(conn!=null){					
					conn.close();
				}
			} catch (SQLException e) {
				log.error("数据库关闭故障>>>>>",e);
			}
		}
	}
	
	
	/**
	 * 获取利用率
	 * @param objIds
	 * @param token
	 * @param carrier
	 * @param nodeConf
	 * @return
	 * @throws IOException
	 */
	@Deprecated
	public  String getServerRealTime(String objIds,String token,String carrier,NodeConfig nodeConf) throws Exception{
		String originalJson = null;
		
		JSONObject json = JSONObject.parseObject(token);
        String tokenId = json.getString("data");
		
        String kpi ="{\"virtrualkpi\":[\"cpuusage\",\"memusage\"],"
        		+ "\"diskstate\":[\"diskusage\"],"
			    + "\"commonstatus\":[\"status\"]}";
   
        String urlEncodeObjIds = URLEncoder.encode(objIds,"utf-8");
        String urlEncodekpi = URLEncoder.encode(kpi,"utf-8");
		try {
			Object serverList = new HttpsClientUtil().sendRequest("/oc/v2.3/monitors/server/realtime?&object_ids="+urlEncodeObjIds+ "&kpi_groups="+ urlEncodekpi, RequestType.GET, null, tokenId,nodeConf);
			new HttpsClientUtil().sendRequest("/oc/v2.3/tokens", RequestType.DELETE, null, tokenId,nodeConf);
			
			originalJson=String.valueOf(serverList);
			
			CommonHttp.saveOrginal("state"+carrier, originalJson, new Date());
			
		} catch (Exception e) {
			CommonHttp.saveOrginal("exception",ProdUtils.exception(e), new Date());
			throw e;
		}
		
		return originalJson;
	}
	
	
	
	
}
